package org.chouy.json;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Package: org.chouy.json
 * @ClassName: JsonTest
 * @Description: java类作用描述
 * @Author: Zhouy
 * @CreateDate: 2017/12/22 下午10:18
 * @UpdateUser: 更新者
 * @UpdateDate: 2017/12/22 下午10:18
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class JsonTest {
    public static void main(String[] args) {



        //解析Json--传入Json字符串111111
        JSONObject my_json = new JSONObject(CreateJson());
        int total = my_json.getInt("total");
        System.out.println("总数为："+total);

        String class_name = (String) my_json.get("class");
        System.out.println("班级为："+class_name);

        JSONArray jsonArray = my_json.getJSONArray("members");

        Iterator iterator=jsonArray.iterator();
        while (iterator.hasNext()){
            JSONObject jsonObject= (JSONObject) iterator.next();
            System.out.println("姓名："+jsonObject.getString("name")+"; 年龄："+jsonObject.getInt("age")+"; 分数："+jsonObject.getInt("score"));
        }

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println("姓名："+jsonObject.getString("name")+"; 年龄："+jsonObject.getInt("age")+"; 分数："+jsonObject.getInt("score"));
        }
    }

    public static String CreateJson(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("class", "二年级");
        jsonObject.put("total", 2);

        JSONArray members=new JSONArray();
        //第一个同学
        JSONObject member1=new JSONObject();
        member1.put("name", "李小红");
        member1.put("age", 18);
        member1.put("score", 95);
        members.put(member1);

        //第二个同学
        JSONObject member2=new JSONObject();
        member2.put("name", "王尼玛");
        member2.put("age", 28);
        member2.put("score", 85);
        members.put(member2);

        jsonObject.put("members", members);
        System.out.println(jsonObject.toString());
        return jsonObject.toString();

    }


}
